#!/usr/bin/env python3
"""
视频转录 HTTP API 服务 - 精简版
"""

import json
import logging
import sys
from pathlib import Path
from flask import Flask, request, jsonify
from flask_cors import CORS

# 添加父目录到路径以便导入 src 模块
sys.path.insert(0, str(Path(__file__).parent.parent))

from src.core.transcriber import VideoTranscriber
from src.core.utils import setup_logger, PathProxy

# 加载配置
with open('config.json', 'r', encoding='utf-8') as f:
    config = json.load(f)

# 初始化
app = Flask(__name__)
CORS(app)
logger = setup_logger(config['log'])
path_proxy = PathProxy(config.get('path_proxy', {}))
transcriber = VideoTranscriber(config)

logger.info("服务初始化完成")


@app.route('/health', methods=['GET'])
def health():
    """健康检查"""
    return jsonify({
        'status': 'ok',
        'model': config['model']['name'],
        'device': config['model']['device']
    })


@app.route('/transcribe', methods=['POST'])
def transcribe():
    """
    转录视频

    请求:
        {
            "video_path": "/api/video.mp4",  // 支持代理路径
            "model": "small",                 // 可选
            "language": "zh"                  // 可选
        }

    响应:
        {
            "success": true,
            "data": {
                "text": "转录文本",
                "language": "zh",
                "duration": 120.5,
                "segments_count": 15
            }
        }
    """
    try:
        data = request.get_json()

        if not data or 'video_path' not in data:
            return jsonify({
                'success': False,
                'error': '缺少 video_path 参数'
            }), 400

        # 路径代理转换
        video_path = data['video_path']
        real_path = path_proxy.resolve(video_path)

        logger.info(f"请求路径: {video_path}")
        if real_path != video_path:
            logger.info(f"代理转换: {real_path}")

        # 检查文件是否存在
        if not Path(real_path).exists():
            return jsonify({
                'success': False,
                'error': f'文件不存在: {video_path}'
            }), 404

        # 获取可选参数
        language = data.get('language', 'zh')

        # 执行转录
        result = transcriber.transcribe(real_path, language=language)

        # 返回结果
        return jsonify({
            'success': True,
            'data': {
                'text': result['text'],
                'language': result['language'],
                'duration': result['duration'],
                'segments_count': result['segments_count'],
                'output_files': result['output_files']
            }
        })

    except FileNotFoundError as e:
        logger.error(f"文件不存在: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 404

    except Exception as e:
        logger.error(f"转录错误: {str(e)}", exc_info=True)
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/batch', methods=['POST'])
def batch():
    """
    批量转录

    请求:
        {
            "video_paths": ["/api/video1.mp4", "/api/video2.mp4"],
            "language": "zh"
        }

    响应:
        {
            "success": true,
            "data": {
                "total": 2,
                "success": 2,
                "failed": 0,
                "results": [...]
            }
        }
    """
    try:
        data = request.get_json()

        if not data or 'video_paths' not in data:
            return jsonify({
                'success': False,
                'error': '缺少 video_paths 参数'
            }), 400

        video_paths = data['video_paths']
        language = data.get('language', 'zh')

        results = []
        success_count = 0
        failed_count = 0

        for video_path in video_paths:
            try:
                # 路径代理转换
                real_path = path_proxy.resolve(video_path)

                # 转录
                result = transcriber.transcribe(real_path, language=language)
                results.append({
                    'video': video_path,
                    'success': True,
                    'duration': result['duration']
                })
                success_count += 1

            except Exception as e:
                logger.error(f"转录失败 {video_path}: {str(e)}")
                results.append({
                    'video': video_path,
                    'success': False,
                    'error': str(e)
                })
                failed_count += 1

        return jsonify({
            'success': True,
            'data': {
                'total': len(video_paths),
                'success': success_count,
                'failed': failed_count,
                'results': results
            }
        })

    except Exception as e:
        logger.error(f"批量转录错误: {str(e)}", exc_info=True)
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


if __name__ == '__main__':
    server_config = config['server']

    print(f"""
    ========================================
    视频转录 API 服务
    ========================================
    地址: http://{server_config['host']}:{server_config['port']}
    模型: {config['model']['name']}
    设备: {config['model']['device']}

    API 端点:
    - GET  /health       健康检查
    - POST /transcribe   转录视频
    - POST /batch        批量转录

    路径代理:
{chr(10).join(f"    - {k} -> {v['target']}" for k, v in config.get('path_proxy', {}).items())}
    ========================================
    """)

    app.run(
        host=server_config['host'],
        port=server_config['port'],
        debug=False
    )
